package com.shop.shopserver.controller.user;

import com.shop.shopcommon.context.SecurityContext;
import com.shop.shopcommon.result.Result;
import com.shop.shoppojo.dto.UserRegisterDTO;
import com.shop.shoppojo.vo.UserInfoVO;
import com.shop.shoppojo.vo.UserIsLoginVO;
import com.shop.shopserver.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.shop.shopcommon.constant.MessageConstant.GET_NOTE_CODE_SUCCESS;
import static com.shop.shopcommon.constant.MessageConstant.SUCCESS;

@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/test")
    @ApiOperation(value = "测试接口")
    public String test() {
        System.out.println("test");
        System.out.println("111");
        return "test";
    }

    /**
     * 查询用户信息
     * @return
     */
    @GetMapping("getUserInfo")
    @ApiOperation(value = "查询用户信息")
    public Result<UserInfoVO> getUserInfo(){
        UserInfoVO userInfoVO=userService.getUserInfo();
        return Result.success(userInfoVO,SUCCESS);
    }

    /**
     * 获取短信验证码
     * @return Result<String>
     */
    @GetMapping("/getNoteCode")
    @ApiOperation(value = "获取短信验证码")
    public Result<String> getNoteCode(@RequestParam String phone) throws Exception {
        String noteCode = userService.getNoteCode(phone);
        return Result.success(noteCode,GET_NOTE_CODE_SUCCESS);
    }

    /**
     * 测试获取当前登录用户名
     */
    @GetMapping("/getC")
    @ApiOperation(value = "获取当前登录用户名")
    public void getC(){
        System.out.println(SecurityContext.getUsername());
    }


    /**
     * 用户注册
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO)  {
        userService.register(userRegisterDTO);
        return Result.success(null,SUCCESS);
    }

    /**
     * 验证用户是否登陆
     */
    @GetMapping("/isLogin")
    public Result <UserIsLoginVO> checkLogin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //通过判断是否为匿名用户判断是否登录
        if (authentication.getPrincipal()==null || authentication.getPrincipal().equals("anonymousUser")) {
            return Result.success(new UserIsLoginVO(false),SUCCESS);
        }else {
            return Result.success(new UserIsLoginVO(true),SUCCESS);
        }
    }

}
